package com.example.book_test.controller;

import com.example.book_test.service.UserService;
import com.example.book_test.constant.Constants;
import com.example.book_test.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;


@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public boolean login(String userName, String password, HttpSession session){
        //账号或密码为空
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return false;
        }
        UserInfo userInfo = userService.queryUserByName(userName);
        if (userInfo == null || userInfo.getId() <= 0){
            //如果找不到或者结果不对，就返回false
            return false;
        }
        //账号密码正确

        if(userInfo!=null && password.equals(userInfo.getPassword())){
            //存储在Session中
            userInfo.setPassword("");
            //如果不指向存储用户名字，想知道更多信息，可以把整个userInfo存进去
            session.setAttribute(Constants.SESSION_USER_KEY,userInfo);
            return true;
        }
        return false;
    }
}
